package thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ServerPlus {
    private ServerSocket serverSocket;

    public ServerPlus() {
        try {
             serverSocket = new ServerSocket(9090);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待连接");
                Socket socket = serverSocket.accept();
                System.out.println("连接成功");
                //启动线程负责与客户端交互
                Runnable r = new ClientHandler(socket);
                Thread t = new Thread(r);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;//记录客户端的IP地址

        public ClientHandler(Socket socket) {
            this.socket = socket;
            this.host = socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {

            try {//run方法里 要用到外部的值，但是方法无法传递参数时
                //建立一个带参数的构造器  然后赋值给成员属性  类中方法共享成员属性
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String temp;
                //Thread t = new Thread();
                while ((temp = br.readLine()) != null) {
                    System.out.println(host + "说" + temp);
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        ServerPlus sp = new ServerPlus();
        sp.start();
    }
}
